/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.biz.modular.xsjbxx.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.mybatisflex.core.FlexGlobalConfig;
import com.mybatisflex.core.datasource.DataSourceKey;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.solon.service.impl.ServiceImpl;
import com.zaxxer.hikari.HikariDataSource;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.data.annotation.Transaction;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.biz.modular.xsjbxx.entity.JwXsjbxx;
import vip.xiaonuo.biz.modular.xsjbxx.mapper.JwXsjbxxMapper;
import vip.xiaonuo.biz.modular.xsjbxx.param.JwXsjbxxAddParam;
import vip.xiaonuo.biz.modular.xsjbxx.param.JwXsjbxxEditParam;
import vip.xiaonuo.biz.modular.xsjbxx.param.JwXsjbxxIdParam;
import vip.xiaonuo.biz.modular.xsjbxx.param.JwXsjbxxPageParam;
import vip.xiaonuo.biz.modular.xsjbxx.service.JwXsjbxxService;
import vip.xiaonuo.common.util.CommonDbUtil;
import vip.xiaonuo.dev.modular.config.service.DevConfigService;
import vip.xiaonuo.sys.modular.role.entity.SysRole;
import vip.xiaonuo.sys.modular.role.param.SysRoleGrantUserParam;
import vip.xiaonuo.sys.modular.role.service.impl.SysRoleServiceImpl;
import vip.xiaonuo.sys.modular.user.entity.SysUser;
import vip.xiaonuo.sys.modular.user.param.SysUserImportParam;
import vip.xiaonuo.sys.modular.user.service.impl.SysUserServiceImpl;

import java.util.Arrays;
import java.util.List;

/**
 * 学生信息Service接口实现类
 *
 * @author lrw
 * @date  2025/02/09 10:45
 **/
@Component
public class JwXsjbxxServiceImpl extends ServiceImpl<JwXsjbxxMapper, JwXsjbxx> implements JwXsjbxxService {
    @Inject
    public DevConfigService devConfigService;
    @Inject
    private SysUserServiceImpl sysUserServiceImpl;
    @Inject
    private SysRoleServiceImpl sysRoleServiceImpl;
    @Override
    public Page<JwXsjbxx> page(JwXsjbxxPageParam jwXsjbxxPageParam) {
        String xh=jwXsjbxxPageParam.getXh();
        String xm=jwXsjbxxPageParam.getXm();
        String xzb=jwXsjbxxPageParam.getXzb();
        String yxmc=jwXsjbxxPageParam.getYxmc();
        String rxnf=jwXsjbxxPageParam.getRxnf();
        String sfzx=jwXsjbxxPageParam.getSfzx();
        if(ObjectUtil.isEmpty(xh) && ObjectUtil.isEmpty(xm)
                && ObjectUtil.isEmpty(xzb) && ObjectUtil.isEmpty(yxmc)
                && ObjectUtil.isEmpty(rxnf)) return null;

        try {
        HikariDataSource ds = CommonDbUtil.getTmpDs("/jwdb.properties");
        FlexGlobalConfig.getDefaultConfig().getDataSource().addDataSource("jw", ds);
        DataSourceKey.use("jw");//使用新的数据源
        QueryWrapper queryWrapper = new QueryWrapper();
            if(ObjectUtil.isNotEmpty(xh)) {
                queryWrapper.like(JwXsjbxx::getXh, xh);
            }
        if(ObjectUtil.isNotEmpty(xm)) {
            queryWrapper.like(JwXsjbxx::getXm, xm);
        }
        if(ObjectUtil.isNotEmpty(xzb)) {
            queryWrapper.like(JwXsjbxx::getXzb, xzb);
        }
        if(ObjectUtil.isNotEmpty(yxmc)) {
            queryWrapper.like(JwXsjbxx::getYxmc, yxmc);
        }
        if(ObjectUtil.isNotEmpty(sfzx)) {
            queryWrapper.eq(JwXsjbxx::getSfzx, sfzx);
        }
        if(ObjectUtil.isNotEmpty(rxnf)) {
            queryWrapper.eq(JwXsjbxx::getRxnf, rxnf);
        }
        if(ObjectUtil.isAllNotEmpty(jwXsjbxxPageParam.getSortField(), jwXsjbxxPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(jwXsjbxxPageParam.getSortOrder());
            queryWrapper.orderBy(StrUtil.toUnderlineCase(jwXsjbxxPageParam.getSortField()),jwXsjbxxPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()));
        } else {
            queryWrapper.orderBy(JwXsjbxx::getXh);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
        }catch (Exception e){
            return null;
        }finally{
            DataSourceKey.clear();
        }
    }

    @Transaction
    @Override
    public void add(JwXsjbxxAddParam jwXsjbxxAddParam) {
        JwXsjbxx jwXsjbxx = BeanUtil.toBean(jwXsjbxxAddParam, JwXsjbxx.class);
        this.save(jwXsjbxx);
    }

    @Transaction
    @Override
    public void edit(JwXsjbxxEditParam jwXsjbxxEditParam) {
        JwXsjbxx jwXsjbxx = this.queryEntity(jwXsjbxxEditParam.getXh());
        BeanUtil.copyProperties(jwXsjbxxEditParam, jwXsjbxx);
        this.updateById(jwXsjbxx);
    }

    @Transaction
    @Override
    public void delete(List<JwXsjbxxIdParam> jwXsjbxxIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(jwXsjbxxIdParamList, JwXsjbxxIdParam::getXh));
    }

    @Override
    public JwXsjbxx detail(JwXsjbxxIdParam jwXsjbxxIdParam) {
        return this.queryEntity(jwXsjbxxIdParam.getXh());
    }

    @Override
    public JwXsjbxx queryEntity(String id) {
        JwXsjbxx jwXsjbxx = this.getById(id);
        if(ObjectUtil.isEmpty(jwXsjbxx)) {
            throw new CommonException("学生信息不存在，id值为：{}", id);
        }
        return jwXsjbxx;
    }
    @Override

    public JSONObject syncupd(JwXsjbxxPageParam jwXsjbxxPageParam) {
        HikariDataSource ds = CommonDbUtil.getTmpDs("/jwdb.properties");
        FlexGlobalConfig.getDefaultConfig().getDataSource().addDataSource("jw", ds);
        DataSourceKey.use("jw");//使用新的数据源
        QueryWrapper queryWrapper = new QueryWrapper();
        if(ObjectUtil.isNotEmpty(jwXsjbxxPageParam.getXh())) {
            queryWrapper.like(JwXsjbxx::getXh, jwXsjbxxPageParam.getXh());
        }
        if(ObjectUtil.isNotEmpty(jwXsjbxxPageParam.getXm())) {
            queryWrapper.like(JwXsjbxx::getXm, jwXsjbxxPageParam.getXm());
        }
        if(ObjectUtil.isNotEmpty(jwXsjbxxPageParam.getXzb())) {
            queryWrapper.like(JwXsjbxx::getXzb, jwXsjbxxPageParam.getXzb());
        }
        if(ObjectUtil.isNotEmpty(jwXsjbxxPageParam.getYxmc())) {
            queryWrapper.like(JwXsjbxx::getYxmc, jwXsjbxxPageParam.getYxmc());
        }
        if(ObjectUtil.isNotEmpty(jwXsjbxxPageParam.getRxnf())) {
            queryWrapper.like(JwXsjbxx::getRxnf, jwXsjbxxPageParam.getRxnf());
        }
        if(ObjectUtil.isNotEmpty(jwXsjbxxPageParam.getSfzx())) {
            queryWrapper.eq(JwXsjbxx::getSfzx, jwXsjbxxPageParam.getSfzx());
        }

        List<JwXsjbxx> jwXsjbxxList = this.list(queryWrapper);
        FlexGlobalConfig.getDefaultConfig().getDataSource().removeDatasource("jw");
        return doImport(jwXsjbxxList);
    }
    @Transaction
    public JSONObject doImport(List<JwXsjbxx> jwXsjbxxList){
        try {
            int successCount = 0;
            int errorCount = 0;
            JSONArray errorDetail = JSONUtil.createArray();
            //提前读入所有用户，减少反复查询数据库；当用户数据较多时，内存压力会较大
            String orgName=devConfigService.getValueByKey("ORG_NAME");
            List<SysUser> allUserList = sysUserServiceImpl.list();
            for (int i = 0; i < jwXsjbxxList.size(); i++) {
                SysUserImportParam sysUserImportParam = new SysUserImportParam();
                JwXsjbxx jwXsjbxx = jwXsjbxxList.get(i);
                sysUserImportParam.setAccount(jwXsjbxx.getXh());
                sysUserImportParam.setName(jwXsjbxx.getXm());
                sysUserImportParam.setOrgName(orgName+"-"+jwXsjbxx.getYxmc()+"-"+jwXsjbxx.getXzb());
                sysUserImportParam.setIdCardNumber(jwXsjbxx.getSfzh());
                sysUserImportParam.setPositionName("学生");
                JSONObject jsonObject = sysUserServiceImpl.doImport(allUserList, sysUserImportParam, i);
                if (jsonObject.getBool("success")) {
                    successCount += 1;
                    String userid = jsonObject.getStr("id");
                    QueryWrapper queryWrapper = new QueryWrapper();
                    queryWrapper.eq(SysRole::getName,"学生");
                    SysRole sysRole=sysRoleServiceImpl.getOne(queryWrapper);
                    String roleid=sysRole.getId();//sysRoleServiceImpl.queryEntity("学生").getId();
                    SysRoleGrantUserParam sysRoleGrantUserParam=new SysRoleGrantUserParam();
                    sysRoleGrantUserParam.setId(roleid);
                    sysRoleGrantUserParam.setGrantInfoList(Arrays.asList(userid));
                    sysRoleServiceImpl.grantUser(sysRoleGrantUserParam);
                } else {
                    errorCount += 1;
                    errorDetail.add(jsonObject);
                }
            }
            return JSONUtil.createObj()
                    .set("totalCount", jwXsjbxxList.size())
                    .set("successCount", successCount)
                    .set("errorCount", errorCount)
                    .set("errorDetail", errorDetail);
        } catch (Exception e) {
            throw new CommonException("学生同步失败");
        }
    }
}
